# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
	
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  # Scrub sensitive parameters from your log
  # filter_parameter_logging :password

  # Couriers can get their 
  before_filter :authorize, :except => [:login,
		:help_index, :help_items, :help_couriers, :help_users, :help_locations, :help_routes, 
		:help_checklists, :help_android]
  
protected

  # check that the user is logged in
  def authorize
	@current_user = User.find_by_id(session[:user_id])
	unless @current_user
	  session[:original_uri] = request.request_uri
	  flash[:notice] = "Please log in"
	  redirect_to login_path
	end
  end

  helper_method :generate_container
  def generate_container(item)
	@container = item.contained_by
	if @container
		@container_type = @container.item_type ? @container.item_type.item_type : "Invalid Item"
		@container_id = @container.identifiers.first ? @container.identifiers.first.identifier_value : "Invalid ID"
		@bag_link_text = @container_type + " " + @container_id
	end
  end

  helper_method :get_status
  def get_status(item, checkins)
	if item.lost_item and not item.lost_item.resolved
		@status = "Lost" 
	else
		if checkins.first 
			if checkins.first.action == 'initial_checkin' 
				@status = "Waiting Pickup" 
			elsif checkins.first.action == 'pick_up' 
				@status = "In transit" 
			elsif checkins.first.action == 'drop_off' 
				@status = "Delivered" 
			end 
		else 
			@status = "Unknown" 
		end 
	end 
	
	@status
  end
  
  # Show the permissions error page
  def permissions_error_page
    respond_to do |format|
        format.html do
            @error_url = request.url
            @title = "Invalid Permissions"
            render 'errors/permissions', :layout => 'simple', :status => :forbidden
        end
        format.json { head :forbidden }
    end
  end
  
public

  # Check that the user has the correct permissions
  def authorize_permissions(vars)
    # TODO: Fix this so that it isn't a controller global variable. Devs should
    # be able to access @current_user.permission_level if they need this.
    @user_permission = @current_user.permission_level

    if vars[:blocked_permissions] && 
       vars[:blocked_permissions].include?(@current_user.permission_level)
      permissions_error_page
    end
  end
end
